package com.lyy.service.impl;

import com.lyy.dao.IAccountDao;
import com.lyy.domain.Account;
import com.lyy.service.IAccountService;
import com.lyy.utils.TransactionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AccountServiceImpl implements IAccountService {

    @Autowired
    @Qualifier(value = "accountDaoImpl2")
    private IAccountDao accountDao;

    @Override
    public List<Account> findAll() {
        return accountDao.findAll();
    }

    @Override
    public void insert(Account account) {
        accountDao.insert(account);
    }

    @Override
    public Account findById(String id) {
        return accountDao.findById(id);
    }

    @Override
    public void delete(String id) {
        accountDao.delete(id);
    }

    @Override
    public String transfer(String sourceId, String targetId, float money) {
        Account sourceAccount = accountDao.findById(sourceId);
        Account targetAccount = accountDao.findById(targetId);
        System.out.println("转账前:" + sourceAccount + "," + targetAccount);

        //转账
        sourceAccount.setMoney(sourceAccount.getMoney() - money);
        targetAccount.setMoney(targetAccount.getMoney() + money);

        //更新数据库
        accountDao.updateMoney(sourceId, sourceAccount.getMoney());
        //int a=1/0;//模拟发生异常
        accountDao.updateMoney(targetId, targetAccount.getMoney());

        Account sourceAccount2 = accountDao.findById(sourceId);
        Account targetAccount2 = accountDao.findById(targetId);
        System.out.println("转账后:" + sourceAccount2 + "," + targetAccount2);
        return "转账成功";
    }
}
